package com.stars.home.utils

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import android.widget.Toast
import com.qmuiteam.qmui.skin.QMUISkinManager
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet.BottomGridSheetBuilder
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog
import com.stars.home.R
import com.yanzhenjie.permission.Action
import com.yanzhenjie.permission.AndPermission
import com.zhy.http.okhttp.OkHttpUtils
import com.zhy.http.okhttp.callback.FileCallBack
import okhttp3.Call
import java.io.File
import java.io.FileNotFoundException
import java.util.*


/**
 * 分享给好友，朋友圈，保存到本地
 *
 *on 2020/10/10
 */
object ShareWxDilaog {

    var chose = 1
    private const val title = "分享"

    var tipDialog: QMUITipDialog? = null
    private var downimg: String? = null
    private val uriArrayList = ArrayList<Uri>() //下载到本地的图片的集合


    fun show(context: Context, url: String) {
        var TAG_SHARE_WECHAT_FRIEND = 0
        var TAG_SHARE_WECHAT_MOMENT = 1
        var TAG_SHARE_LOCAL = 3
        val builder = BottomGridSheetBuilder(context)
        builder.addItem(R.drawable.ic_more_friend, "分享到微信", TAG_SHARE_WECHAT_FRIEND, BottomGridSheetBuilder.FIRST_LINE)
                .addItem(R.drawable.ic_more_moment, "分享到朋友圈", TAG_SHARE_WECHAT_MOMENT, BottomGridSheetBuilder.FIRST_LINE)
                .addItem(R.drawable.ic_more_save, "保存到本地", TAG_SHARE_LOCAL, BottomGridSheetBuilder.FIRST_LINE)
                .setAddCancelBtn(true)
                .setSkinManager(QMUISkinManager.defaultInstance(context))
                .setOnSheetItemClickListener { dialog, itemView ->
                    dialog.dismiss()
                    val tag = itemView.tag as Int
                    when (tag) {
                        TAG_SHARE_WECHAT_FRIEND -> {//微信


                            //分享给好友
                            chose = 1
                            setShareImages(context,url)
                        }
                        TAG_SHARE_WECHAT_MOMENT -> {//朋友圈


                            //分享给朋友圈
                            chose = 2
                            setShareImages(context,url)


                        }
                        TAG_SHARE_LOCAL -> {//保存到本地

                            saveImageToGallery(context,url)
                        }

                    }
                }.build().show()
    }


    /**
     * 保存到系统相册
     */
    @SuppressLint("WrongConstant")
    fun saveImageToGallery(context: Context,url: String) {
        AndPermission.with(context)
                .runtime()
                .permission(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA
                )
                .onGranted(Action<List<String?>?>
                /**
                 * @param data
                 */
                /**
                 * @param data
                 */
                {
                    setSaveImg(context,url)
                }
                ).start()
    }

    fun setSaveImg(context: Context,url: String) {

        tipDialog = QMUITipDialog.Builder(context)
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                .setTipWord("正在保存图片...")
                .create()


        Thread(Runnable {
            val bitmap: Bitmap = SaveLocalUtils.returnBitMap(url)
            SaveLocalUtils.saveBitmap(context, bitmap, "loc" + System.currentTimeMillis() + ".png")
            //                SaveLocalUtils.saveBmp2Gallery(
//                        getContext(), bitmap,
//                        "loc" + System.currentTimeMillis());
            (context as Activity).runOnUiThread {
                this.tipDialog!!.dismiss()
                Toast.makeText(context, "图片已保存在手机相册下！", Toast.LENGTH_LONG).show()
                //Toasts.toast(context, "图片已保存在相册CANDYIMG文件夹下！");

            }
        }).start()
    }


    fun setShareImages(context: Context, url: String) {
        tipDialog = QMUITipDialog.Builder(context)
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                .setTipWord("正在保存图片...")
                .create()


        //下载图片
        startDownImg(url, context)

    }

    /**
     * @param photoPathL 下载图片
     */
    private fun startDownImg(photoPathL: String, con: Context) {

        //先下载图片
        okHttpSaveImg(photoPathL, 1, con)
    }

    private fun okHttpSaveImg(imgUrl: String, position: Int, con: Context?) {
        val filePath: String = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            con!!.filesDir.absolutePath
        } else {
            getSDPath() + "/revoeye/"
        }
        if (con == null) {
            // Toasts.toast(con, con.getString(R.string.action_share)+con.getString(R.string.fail)+con.getString(R.string.the_comma)+con.getString(R.string.please_share_it_later));
            return
        }
        OkHttpUtils
                .get()
                .url(imgUrl)
                .build() //
                .execute(object : FileCallBack(filePath, position.toString() + "home.jpg" //
                ) {
                    override fun onError(call: Call, e: Exception, id: Int) {
                        if (con != null) {
                            Log.e("Exception:", e.toString())
                        }
                    }

                    override fun onResponse(response: File, id: Int) {
                        if (con != null) {
                            if (response != null) {
                                val mUri: Uri
                                mUri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                    /**Android 7.0以上的方式 */
                                    //                            mUri = getUriForFile(mContext, "com.muxi.ant.fileprovider", response);
                                    if (con != null) {
                                        Uri.parse(insertImageToSystem(con, response.absolutePath))
                                    } else {
                                        return
                                    }
                                } else {
                                    Uri.fromFile(response)
                                }

                                //uriArrayList.add(mUri);
                                downimg = mUri.toString()
                                if (uriArrayList.size > 0) {
                                    uriArrayList.clear()
                                }
                                uriArrayList.add(Uri.parse(downimg))
                                if (con != null) {
                                    share(con)
                                }
                            }
                        }
                    }
                })
    }


    private fun share(context: Context) {


        tipDialog!!.dismiss()

        if (chose == 1) { //微信好友
            val uriToImage = Uri.parse(downimg)

            //图片
            val shareIntent = Intent()
            //发送图片到朋友圈
            //ComponentName comp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareToTimeLineUI");
            //发送图片给好友。
            val comp = ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareImgUI")
            shareIntent.component = comp
            shareIntent.action = Intent.ACTION_SEND
            shareIntent.putExtra(Intent.EXTRA_STREAM, uriToImage)
            shareIntent.type = "image/jpeg"
            context.startActivity(Intent.createChooser(shareIntent, title))

        }
        if (chose == 2) { //微信朋友圈
            val componentName = ComponentName("com.tencent.mm",
                    "com.tencent.mm.ui.tools.ShareToTimeLineUI")
            var intent = Intent()
            intent.component = componentName
            intent.type = "image/*"
            if (uriArrayList.size > 1) {
                intent.action = Intent.ACTION_SEND_MULTIPLE
                intent.putExtra(Intent.EXTRA_STREAM, uriArrayList) //图片数据（支持本地图片的Uri形式）
            } else if (uriArrayList.size == 1) {
                intent.action = Intent.ACTION_SEND
                intent.putExtra(Intent.EXTRA_STREAM, uriArrayList[0]) //图片数据（支持本地图片的Uri形式）
            }
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION
                    or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
            intent.putExtra("Kdescription", title)
            intent.putExtra(Intent.EXTRA_TEXT, title) //正常使用的文字

            context.startActivity(intent)


        }
    }


    private const val SHARE_PIC_NAME = "Name"

    private fun insertImageToSystem(context: Context, imagePath: String): String? {
        var url: String? = ""
        try {
            url = MediaStore.Images.Media.insertImage(context.contentResolver, imagePath, SHARE_PIC_NAME, "你对图片的描述")
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
        }
        return url
    }

    fun getSDPath(): String? {
        var sdDir: File? = null
        val sdCardExist = Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED //判断sd卡是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory() //获取跟目录
        }
        return sdDir.toString()
    }


}
